<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>去除字符串首尾空格</title>
    <script>
        //定义一个函数，功能是去除字符串开头及末尾的空格
        //[10个空格]abc[2空格]def[6空格]
        //思路：使用charAt和substring去除头尾空格
        function clearTrim(string) {
            let str1 = string+"";
            for(i=0;i<str1.length;i++){
                //遍历每一位字符
                let char = str1.charAt(i);
                //不是空格截取
                if (char === ' ') {
                    continue;
                }
                let str = str1.substring(i);
                for (j = str.length - 1; j >= 0; j--) {
                    let char = str.charAt(j);
                    if (char === ' ') {
                        continue;
                    }
                    let s = str.substring(0, j);
                    return s;
                }
            }
        }
        let str = "          abc  def      ";
        let substr = clearTrim(str);
        alert(substr);
    </script>
</head>
<body>

</body>
</html>